package com.client;

import com.server.NettyTcpServer;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.socket.SocketChannel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Component
@ConditionalOnBean(NettyTcpServer.class)
public class NettyTcpClient {
    @Resource
    private Bootstrap bootstrap;
    @Resource
    private NettyTcpServer nettyTcpServer;

    @Value("${tcp.port}")
    private int tcpPort;

    @Value(("${tcp.ip}"))
    private String serverIp;

    private Channel channel;

    public void connect() throws InterruptedException {
        // 发起异步连接
        ChannelFuture future = bootstrap.connect(serverIp, tcpPort).sync();
        channel = future.channel();
        if (!future.isSuccess()) {
            future.cause().printStackTrace();
        }

    }

    @PreDestroy
    public void stop() {
        channel.closeFuture();
    }

    public void sendMessage(String msg) throws UnsupportedEncodingException, InterruptedException {
        if(!channel.isActive()){
            this.connect();
        }
        ByteBuf byteBuf = Unpooled.wrappedBuffer(msg.getBytes("utf-8"));
        channel.writeAndFlush(byteBuf);
    }

    /**
     * 在启动servlet的时候，启动netty
     * @throws Exception
     */
    @PostConstruct
    public void start() throws InterruptedException {
        this.connect();
//        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(()->{
//            try {
//                this.sendMessage("ping");
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        },5,5, TimeUnit.SECONDS);
    }
}
